<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_pddke/model')->方法名();
	https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.search&keyword%3D
	https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.search
*/
namespace jy_pddke;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	
	public function hq_taoid($taourl) {//根据淘宝地址获取淘宝商品id
		$strurl = strtolower ( $taourl);
		if (strpos ( $strurl, 's' ) !== false) {
			$arr = explode ( '?', $taourl);
			$arr = explode ( '&', $arr [1] );
			$NO = 0;
			foreach ( $arr as $k => $v ) {
				if (is_string ( $v )) {
					//判断是否含有id
					if (strpos ( $v, 's' ) !== false) {
						//处理含有item或者num项 返还id数
						if (strpos ( $v, 'item' ) !== false || strpos ( $v, 'num' ) !== false) {
							//echo $v,'<br/>';
							$i = strrpos ( $v, '=' );
							$str = substr ( $v, $i + 1 );
							if (is_numeric ( $str )) {
								return $NO = $str;
							}
						} else {
							//echo $v,'<br/>';
							$i = strrpos ( $v, '=' );
							$str = substr ( $v, $i + 1 );
							$x = strlen ( $str );
							if (is_numeric ( $str )) {
								if ($x ==11) {
									$NO = $str;
								} else if ($NO == 0 || ($x > 9 && $x < 11)) {
									$NO = $str;
								}
							}
						}
					}
				}
			}
			return $NO;
		}
	}
	public function getgoodsinfo($id,$pid=0,$search_id=0,$plan_type=0,$zs_duo_id=0){
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \PopHttpClient($clientId, $clientSecret);
		$request = new \PddDdkGoodsDetailRequest();
		$CustomParameters=array('uid'=>$mid);
		$request->setCustomParameters(json_encode($CustomParameters));
		$goodsIdList = array();
		$goodsIdList[] = $id;
		$request->setGoodsSignList($goodsIdList);
		$request->setPid($pid);
		$request->setPlanType($plan_type);
		$request->setSearchId($search_id);
		$request->setZsDuoId($zs_duo_id);
		try{
			$response = $client->syncInvoke($request, Config::$accessToken);
		} catch(Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取商品详情异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'],'error');
		}
		$content=json_encode($content,JSON_UNESCAPED_UNICODE);
		return $content;
	}
	public function getgoodslist($ids='',$post=array()){
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkGoodsSearchRequest();
		$CustomParameters=array('uid'=>$mid);
		$request->setCustomParameters(json_encode($CustomParameters));
		$ActivityTags=array();
		$ActivityTags[]=$post['activity_tags']?:'';
		$request->setActivityTags($ActivityTags);
		$post['cat_id']=$post['cat_id']?:'';
		$request->setCatId($post['cat_id']);
		if($ids){
			$goodsSignList = array();
			$goodsSignList[] = $ids;
			$request->setGoodsSignList($goodsSignList);
		}
		$request->setIsBrandGoods($post['is_brand_goods']==1?:false);
		$request->setKeyword($post['keyword']?:'');
		$request->setListId();
		$request->setMerchantType($post['merchant_type']?:0);
		//$merchantTypeList = array();
		//$merchantTypeList[] = 0;
		//$request->setMerchantTypeList($merchantTypeList);
		$request->setOptId($post['opt_id']?:'');
		$request->setPage($post['page']?:1);
		$request->setPageSize(100);
		$request->setPid();
		if($post['range_id']){
			$rangeList = array();
			$item = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkGoodsSearchRequest_RangeListItem();
			$item->setRangeFrom($post['range_from']);
			$item->setRangeId($post['range_id']);
			$item->setRangeTo($post['range_to']);
			$rangeList[] = array('range_id'=>$post['range_id'],'range_from'=>$post['range_from'],'range_to'=>$post['range_to']);
			$request->setRangeList($rangeList);
		}
		$request->setSortType(0);
		$request->setWithCoupon(false);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取商品列表异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'].'-'.$content['error_response']['sub_msg'],'error');
		}
		//$content=json_encode($content,JSON_UNESCAPED_UNICODE);
		return $content['goods_search_response'];
	}
	public function getgoodslist_store($mall_id,$post=array()){
		if(!$mall_id){
			exi('请输入店铺ID','error');
		}
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkMallGoodsListGetRequest();
		$request->setMallId($mall_id);
		$request->setPageNumber($post['page']?:1);
		$request->setPageSize(100);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取店铺异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'].'-'.$content['error_response']['sub_msg'],'error');
		}
		return $content['goods_info_list_response'];
	}
	public function getgoodslist_baokuan($post=array()){
		if(!$post['sort_baotype']){
			exi('请输入爆款类型','error');
		}
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkTopGoodsListQueryRequest();
		$request->setLimit($post['limit']?:10);
		$request->setOffset($post['offset']?:1);
		$request->setSortType($post['sort_baotype']?:1);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取爆款异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'].'-'.$content['error_response']['sub_msg'],'error');
		}
		return $content['top_goods_list_get_response'];
	}
	public function getgoodslist_huodong($post=array()){
		if(!$post['theme_id']){
			exi('请输入主题ID','error');
		}
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkThemeGoodsSearchRequest();
		$request->setThemeId($post['theme_id']);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取活动异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'].'-'.$content['error_response']['sub_msg'],'error');
		}
		return $content['theme_list_get_response'];
	}
	//pdd.ddk.goods.promotion.url.generate
	public function getfeeurl($mid,$goodsid,$p_id='',$isexi=false){
		$skuid=pdo_getcolumn('jy_pddke_url',array('goodsid'=>$goodsid,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'skuid');
		if($skuid){
			return false;
		}
		$skuid=pdo_getcolumn('jy_pddke_goods',array('goodsid'=>$goodsid,'uniacid'=>$_SESSION['uniacid']),'skuid');
		if(!$skuid){
			return false;
		}
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$p_id=$p_id?:$basic['siteid'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkGoodsPromotionUrlGenerateRequest();
		$CustomParameters=array('uid'=>$mid);
		$request->setCustomParameters(json_encode($CustomParameters));
		$request->setGenerateMallCollectCoupon(false);
		$request->setGenerateQqApp(false);
		$request->setGenerateSchemaUrl(false);
		$request->setGenerateShortUrl(true);
		$request->setGenerateWeappWebview(true);
		$request->setGenerateWeiboappWebview(false);
		$request->setGenerateWeApp(true);
		$goodsSignList = array();
		$goodsSignList[] = $skuid;
		$request->setGoodsSignList($goodsSignList);
		$request->setMultiGroup(false);
		$request->setPId($p_id);
		//$request->setSearchId();
		//$request->setZsDuoId();
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response']) && $isexi){
			exi('获取链接异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'],'error');
		}
		$res=$content['goods_promotion_url_generate_response']['goods_promotion_url_list'];
		$res[0]['skuid']=$skuid;
		$res[0]['goodsid']=$goodsid;
		$res[0]['mid']=$mid;
		return $res[0];
	}
	//order_sn订单查询接口dd.ddk.order.detail.get
	public function getorder($order_sn){
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddDdkOrderDetailGetRequest();
		$CustomParameters=array('uid'=>$mid);
		$request->setOrderSn($order_sn);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取订单异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'],'error');
		}
		$content=json_encode($content,JSON_UNESCAPED_UNICODE);
		return $content;
	}
	//最后更新时间段增量同步推广订单信息,订单查询接口pdd.ddk.order.list.increment.get
	public function getorderlist($pageIndex=1,$pageSize=20,$type=1,$startTime='',$fields=array()){
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \PopHttpClient($clientId, $clientSecret);
		$request = new \PddDdkOrderListIncrementGetRequest();
		$CustomParameters=array('uid'=>$mid);
		$request->setEndUpdateTime($startTime);
		$request->setPage($pageIndex);
		$request->setPageSize($pageSize);
		$request->setReturnCount(false);
		$endTime=$endTime?:time();
		$request->setStartUpdateTime($endTime);
		try{
			$response = $client->syncInvoke($request, Config::$accessToken);
		} catch(Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取订单列表异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'],'error');
		}
		return $content;
	}
	//获取标签
	public function getgoods_opts(){
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddGoodsOptGetRequest();
		$request->setParentOptId(0);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取标签异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'],'error');
		}
		return $content['goods_opt_get_response'];
	}
	//获取分类
	public function getgoods_cats(){
		include ROOT_D.'/addons/jy_pddke/sdk/vendor/autoload.php';
		$basic=$this->plugin_setting('basic');
		$clientId = $basic['client_id'];
		$clientSecret = $basic['secret'];
		$client = new \Com\Pdd\Pop\Sdk\PopHttpClient($clientId, $clientSecret);
		$request = new \Com\Pdd\Pop\Sdk\Api\Request\PddGoodsCatsGetRequest();
		$request->setParentCatId(0);
		try{
			$response = $client->syncInvoke($request);
		} catch(\Com\Pdd\Pop\Sdk\PopHttpException $e){
			exi($e->getMessage(),'error');
		}
		$content = $response->getContent();
		if(isset($content['error_response'])){
			exi('获取分类异常，错误码：'.$content['error_response']['error_code'].',内容：'.$content['error_response']['error_msg'],'error');
		}
		return $content['goods_cats_get_response'];
	}
	public function creategoods($params){
						if(!$params['goods_name'] || !$params['goods_image_url']){
								exi('获取商品信息失败','error');
						}
						$skuid=pdo_getcolumn('jy_pddke_goods',array('skuid'=>$params['goods_id'],'uniacid'=>$_SESSION['uniacid']),'skuid');
						if($skuid){
							$goodsid=pdo_getcolumn('jy_pddke_goods',array('skuid'=>$params['goods_id'],'uniacid'=>$_SESSION['uniacid']),'goodsid');
							$good=array(
										'title'=>$params['goods_name'],
										'subtitle'=>$params['goods_desc'],
										'image'=>$params['goods_image_url'],
										'images'=>ijson_encode($params['goods_gallery_urls']),
										'salenum'=>$params['sales_tip'],
										'originalprice'=>$params['min_normal_price']/100,
										'price'=>$params['min_group_price']/100,
							);
							pdo_update('jy_weishop_goods',$good,array('id'=>$goodsid,'uniacid'=>$_SESSION['uniacid']));
							$taobao=array(
								'activity_tags'=>ijson_encode($params['activity_tags']),
								'activity_type'=>$params['activity_type'],
								'category_id'=>$params['category_id'],
								'category_name'=>$params['category_name'],
								'cat_ids'=>ijson_encode($params['cat_ids']),
								'clt_cpn_batch_sn'=>$params['clt_cpn_batch_sn'],
								'clt_cpn_discount'=>$params['clt_cpn_discount'],
								'clt_cpn_end_time'=>$params['clt_cpn_end_time'],
								'clt_cpn_min_amt'=>$params['clt_cpn_min_amt'],
								'clt_cpn_quantity'=>$params['clt_cpn_quantity'],
								'clt_cpn_remain_quantity'=>$params['clt_cpn_remain_quantity'],
								'clt_cpn_start_time'=>$params['clt_cpn_start_time'],
								'coupon_discount'=>$params['coupon_discount'],
								'coupon_end_time'=>$params['coupon_end_time'],
								'coupon_min_order_amount'=>$params['coupon_min_order_amount'],
								'coupon_remain_quantity'=>$params['coupon_remain_quantity'],
								'coupon_start_time'=>$params['coupon_start_time'],
								'coupon_total_quantity'=>$params['coupon_total_quantity'],
								'goods_desc'=>$params['goods_desc'],
								'skuid'=>$params['goods_id'],
								'has_coupon'=>$params['has_coupon'],
								'has_mall_coupon'=>$params['has_mall_coupon'],
								'mall_coupon_discount_pct'=>$params['mall_coupon_discount_pct'],
								'mall_coupon_end_time'=>$params['mall_coupon_end_time'],
								'mall_coupon_id'=>$params['mall_coupon_id'],
								'mall_coupon_max_discount_amount'=>$params['mall_coupon_max_discount_amount'],
								'mall_coupon_min_order_amount'=>$params['mall_coupon_min_order_amount'],
								'mall_coupon_remain_quantity'=>$params['mall_coupon_remain_quantity'],
								'mall_coupon_start_time'=>$params['mall_coupon_start_time'],
								'mall_coupon_total_quantity'=>$params['mall_coupon_total_quantity'],
								'mall_cps'=>$params['mall_cps'],
								'mall_id'=>$params['mall_id'],
								'mall_name'=>$params['mall_name'],
								'merchant_type'=>$params['merchant_type'],
								'min_group_price'=>$params['min_group_price'],
								'min_normal_price'=>$params['min_normal_price'],
								'plan_type'=>$params['plan_type'],
								'promotion_rate'=>$params['promotion_rate'],
								'sales_tip'=>$params['sales_tip'],
								'search_id'=>$params['search_id'],
								'service_tags'=>ijson_encode($params['service_tags']),
								'zs_duo_id'=>$params['zs_duo_id'],
							);
							pdo_update('jy_pddke_goods', $taobao,array('skuid'=>$params['goods_id'],'uniacid'=>$_SESSION['uniacid']));
							if($params['click_url']){
								pdo_update('jy_pddke_url', array('url'=>$params['click_url']),array('gid'=>$goodsid,'uniacid'=>$_SESSION['uniacid']));
							}
						}else{
							$good=array(
								'uniacid'=>$_SESSION['uniacid'],
								'title'=>$params['goods_name'],
								'subtitle'=>$params['goods_desc'],
								'image'=>$params['goods_image_url'],
								'images'=>ijson_encode($params['goods_gallery_urls']),
								'salenum'=>$params['sales_tip'],
								'originalprice'=>$params['min_normal_price']/100,
								'price'=>$params['min_group_price']/100,
								'pluginname'=>'jy_pddke',
								'total'=>188,
								'status'=>1,
								'createtime'=>time()
								
							);
							pdo_insert('jy_weishop_goods',$good);
							$goodsid=pdo_insertid();
							$taobao=array(
								'uniacid'=>$_SESSION['uniacid'],
								'goodsid'=>$goodsid,
								'activity_tags'=>ijson_encode($params['activity_tags']),
								'activity_type'=>$params['activity_type'],
								'category_id'=>$params['category_id'],
								'category_name'=>$params['category_name'],
								'cat_ids'=>ijson_encode($params['cat_ids']),
								'clt_cpn_batch_sn'=>$params['clt_cpn_batch_sn'],
								'clt_cpn_discount'=>$params['clt_cpn_discount'],
								'clt_cpn_end_time'=>$params['clt_cpn_end_time'],
								'clt_cpn_min_amt'=>$params['clt_cpn_min_amt'],
								'clt_cpn_quantity'=>$params['clt_cpn_quantity'],
								'clt_cpn_remain_quantity'=>$params['clt_cpn_remain_quantity'],
								'clt_cpn_start_time'=>$params['clt_cpn_start_time'],
								'coupon_discount'=>$params['coupon_discount'],
								'coupon_end_time'=>$params['coupon_end_time'],
								'coupon_min_order_amount'=>$params['coupon_min_order_amount'],
								'coupon_remain_quantity'=>$params['coupon_remain_quantity'],
								'coupon_start_time'=>$params['coupon_start_time'],
								'coupon_total_quantity'=>$params['coupon_total_quantity'],
								'goods_desc'=>$params['goods_desc'],
								'skuid'=>$params['goods_id'],
								'has_coupon'=>$params['has_coupon'],
								'has_mall_coupon'=>$params['has_mall_coupon'],
								'mall_coupon_discount_pct'=>$params['mall_coupon_discount_pct'],
								'mall_coupon_end_time'=>$params['mall_coupon_end_time'],
								'mall_coupon_id'=>$params['mall_coupon_id'],
								'mall_coupon_max_discount_amount'=>$params['mall_coupon_max_discount_amount'],
								'mall_coupon_min_order_amount'=>$params['mall_coupon_min_order_amount'],
								'mall_coupon_remain_quantity'=>$params['mall_coupon_remain_quantity'],
								'mall_coupon_start_time'=>$params['mall_coupon_start_time'],
								'mall_coupon_total_quantity'=>$params['mall_coupon_total_quantity'],
								'mall_cps'=>$params['mall_cps'],
								'mall_id'=>$params['mall_id'],
								'mall_name'=>$params['mall_name'],
								'merchant_type'=>$params['merchant_type'],
								'min_group_price'=>$params['min_group_price'],
								'min_normal_price'=>$params['min_normal_price'],
								'plan_type'=>$params['plan_type'],
								'promotion_rate'=>$params['promotion_rate'],
								'sales_tip'=>$params['sales_tip'],
								'search_id'=>$params['search_id'],
								'service_tags'=>ijson_encode($params['service_tags']),
								'zs_duo_id'=>$params['zs_duo_id'],
								'createtime'=>time()	
							);
							pdo_insert('jy_pddke_goods',$taobao);
							//$data=$this->model()->getfeeurl(1,$params['goodsid']);
							//$this->model()->intfeeurl($data);
						}
				return $goodsid;
	}
	public function intfeeurl($params){
						$goodsid=pdo_getcolumn('jy_pddke_url',array('skuid'=>$params['skuid'],'mid'=>$params['mid'],'uniacid'=>$_SESSION['uniacid']),'goodsid');
						if($goodsid){
							
						}else{
							$taobao=array(
								'uniacid'=>$_SESSION['uniacid'],
								'mid'=>$params['mid'],
								'goodsid'=>$params['goodsid'],
								'skuid'=>$params['skuid'],
								'short_url'=>$params['short_url'],
								'url'=>$params['we_app_web_view_short_url'],
								'mobile_short_url'=>$params['mobile_short_url'],
								'mobile_url'=>$params['mobile_url'],
								'schema_url'=>$params['schema_url'],
								'we_app_id'=>$params['we_app_info']['we_app_id'],
								'we_banner_url'=>$params['we_app_info']['we_banner_url'],
								'we_desc'=>$params['we_app_info']['we_desc'],
								'we_page_path'=>$params['we_app_info']['we_page_path'],
								'we_source_display_name'=>$params['we_app_info']['we_source_display_name'],
								'we_title'=>$params['we_app_info']['we_title'],
								'we_user_name'=>$params['we_app_info']['we_user_name'],
								'we_app_icon_url'=>$params['we_app_info']['we_app_icon_url'],
								'we_app_web_view_short_url'=>$params['we_app_web_view_short_url'],
								'we_app_web_view_url'=>$params['we_app_web_view_url'],
								'createtime'=>time()	
							);
							pdo_insert('jy_pddke_url',$taobao);
						}
	}
	public function createorder($params){
				$orderId=pdo_getcolumn('jy_weishopke_order',array('orderid'=>$params['orderId'],'uniacid'=>$_SESSION['uniacid']),'orderid');
				$goodsid=pdo_getcolumn('jy_jdk_goods',array('skuid'=>$params['goods_id'],'uniacid'=>$_SESSION['uniacid']),'goodsid');
				if($params['finishTime']){
						$status=1;
				}
				if(!$orderId){
					$new_order=array(
						'mid'=>$params['ext1'],
						'goodsid'=>$goodsid,
						'skuid'=>$params['skuId'],
						'orderid'=>$params['orderId'],
						'parentid'=>$params['parentId'],
						'goodsprice'=>$params['price'],
						'total'=>$params['skuNum'],
						'total_price'=>$params['estimateCosPrice'],
						'actualCosPrice'=>$params['actualCosPrice'],//实际计算佣金的
						'actualFee'=>$params['actualFee'],//推客获得的实际佣金（实际计佣金额*佣金比例*最终比例）。如订单完成后发生退款，此金额会更新
						'commissionRate'=>$params['commissionRate'],//佣金比例
						'estimateFee'=>$params['estimateFee'],//推客的预估佣金
						'type'=>'jd',
						'status'=>$status,
						'finishtime'=>$params['finishTime'],
						'createtime'=>$params['orderTime'],
					);
					pdo_insert('jy_weishopke_order',$new_order);
					$orderId=pdo_insertid();
				}else{
					
					$up_order=array(
						'total_price'=>$params['estimateCosPrice'],
						'actualCosPrice'=>$params['actualCosPrice'],
						'actualFee'=>$params['actualFee'],
						'commissionRate'=>$params['commissionRate'],
						'estimateFee'=>$params['estimateFee'],
						'status'=>$status,
						'finishtime'=>$params['finishTime'],
					);
					pdo_update('jy_weishopke_order',$up_order,array('orderid'=>$params['orderId'],'uniacid'=>$_SESSION['uniacid']));
				}
			return $orderId;
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($orderid){
		$this->update('order',array('status'=>1,'finishtime'=>TIMESTAMP),array('id'=>$orderid));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['finishtime <']=$time;
		}
		$commissions=$this->getall('order',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('order'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('order',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type,$wxgid=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'电商客佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}
	
}
?>